<?php
/** 初始化项目 */

use app\util\ConstCode;
use app\util\Mysql;

require '../app/app.php';

if ($_SESSION['username'] == '' || isset($_SESSION["username"]) == false) {
    echo "<script>alert('当前未登录!');location.href='/?c=login';</script>";exit();
}

/**
 * @param $tid
 * @param $htmlContent
 * @return true
 */
function deleteNotUseFile($tid,$htmlContent) {
    $dom = new \DOMDocument();
    // 防止 HTML 解析警告
    libxml_use_internal_errors(true);
    $dom->loadHTML('<?xml encoding="UTF-8">' . $htmlContent);
    libxml_clear_errors();

    $file_array = [];
    // 获取所有 a 标签
    $aTags = $dom->getElementsByTagName('a');
    foreach ($aTags as $aTag) {
        if ($aTag->getAttribute('target') === '附件') {
            $file_array[] = $aTag->getAttribute('href');
        }
    }
    // 获取所有 img 标签
    $imgTags = $dom->getElementsByTagName('img');
    foreach ($imgTags as $imgTag) {
        $file_array[] = $imgTag->getAttribute('src');
    }
    // 获取所有 video 标签
    $imgTags = $dom->getElementsByTagName('source');
    foreach ($imgTags as $imgTag) {
        $file_array[] = $imgTag->getAttribute('src');
    }

    //获取系统中附件信息
    $database = Mysql::init();
    $list = $database->select("more_file", "*",['text_id'=>$tid]);
    foreach ($list as $value){
        if(!in_array($value['file_url'],$file_array)){
            //删除文件
            unlink(APP_PATH.$value['file_url']);
            $database->delete("more_file", ['id'=>$value['id']]);
        }
    }
    return true;
}

if(empty($_POST)){
    $tid = $_GET['tid']??null;
    $database = Mysql::init();
    if(empty($tid)){
        //获取草稿
        $tid = $database->get("text_main", 'tid',[
            'user_id'=>$_SESSION['userInfo']['id'],
            'status'=>ConstCode::STATUS_DRAFT,
        ]);
        if(empty($tid)){
            //创建草稿
            $database->insert("text_main", [
                'user_id'=>$_SESSION['userInfo']['id'],
                'status'=>ConstCode::STATUS_DRAFT]
            );
            $tid = $database->id();
            $database->insert("text_auth", [
                'tid'=>$tid,
            ]);
        }
    }
    //编辑
    $database = Mysql::init();
    $textMain = $database->get("text_main", '*',['tid'=>$tid]);
    $textAuth = $database->get("text_auth", '*',['tid'=>$tid]);
    if(empty($textMain) || empty($textAuth)){
        error('数据不存在！');
    }


    $data = [
        'tid'=>$textMain['tid'],
        'textname'=>$textMain['textname'],
        'main'=>$textMain['main'],
        'status'=>$textMain['status'],
        'gread'=>$textAuth['gread'],
        'otherread'=>$textAuth['otherread'],
    ];
    //渲染页面
    if ($_SESSION['sysgrade'] >= 2) {
        view('article',$data,'admin');
    } else {
        include_once('no.php');
    }
}else{
    //接口
    $database = Mysql::init();

    $tid         = $_POST["tid"]??null;
    $textname   = $_POST["textname"];
    $main       = $_POST["main"];
    $status     = $_POST["status"]??ConstCode::STATUS_DELETE;
    $gread      = $_POST["gread"]??0;
    $otherread  = $_POST["otherread"]??0;
    if ($status === "on") {
        $status = ConstCode::STATUS_NORMAL;
    }

    $textMainData = [
        "textname" => $textname,
        "main" => $main,
        "creator" => $_SESSION['username'],
        "created" => NOW_TIME,
        "status" => $status
    ];
    $textAuthData = [
        "id" => $_SESSION['id'],
        "gid" => $_SESSION['gid'],
        "gread" => $gread,
        "otherread" => $otherread
    ];
    if(empty($tid)){
        //创建文章
        $database->insert("text_main", $textMainData);
        $tid = $database->id();
        $textAuthData['tid'] = $tid;

        $database->insert("text_auth", $textAuthData);

        //删除没有使用的文件
        deleteNotUseFile($tid,$textMainData['main']);
        success("添加成功");
    }else{
        $data = $database->get('text_main','*',["tid" => $tid]);
        //修改文章
        $database->update("text_main", $textMainData,["tid" => $tid]);
        $database->update("text_auth", $textAuthData,["tid" => $tid]);

        //删除没有使用的文件
        deleteNotUseFile($tid,$textMainData['main']);
        if(empty($data['main'])){
            success("添加成功");
        }else{
            success("修改成功");
        }
    }



}